import socket
import re
import os


def show_files(base_path, all_files=None):
    """
    遍历当前目录所有py文件及文件夹
    :param base_path:
    :param path:
    :param all_files:
    :return:
    """
    if all_files is None:
        all_files = []
    file_list = os.listdir(base_path)
    # 准备循环判断每个元素是否是文件夹还是文件，是文件的话，把名称传入list，是文件夹的话，递归
    for file in file_list:
        # 利用os.path.join()方法取得路径全名，并存入cur_path变量，否则每次只能遍历一层目录
        cur_path = os.path.join(base_path, file)
        # 判断是否是文件夹
        if os.path.isdir(cur_path):
            show_files(cur_path, all_files)
        else:
            if not file.endswith('.yml') and not file.endswith('.conf') and not file.endswith('.properties'):
                continue
            else:
                all_files.append(cur_path)
    return all_files


def replace_ip(cur_ip, last_ip, files=None, encode='UTF-8'):
    if files is None:
        files = []
    for file in files:
        file_data = ""
        with open(file, "r", encoding=encode) as f:
            for line in f:
                if last_ip in line:
                    line = line.replace(last_ip,cur_ip)
                file_data += line
        with open(file, "w", encoding=encode) as f:
            f.write(file_data)

def get_local_ip():
    # 获取内网IP
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(('8.8.8.8', 80))
    local_ip = open('local.ip', 'w')
    local_ip.write(s.getsockname()[0])
    print('本地ip是:%s', (s.getsockname()[0]))
    ip = s.getsockname()[0]
    s.close()
    return ip


def get_last_ip():
    f = open('local.ip', 'r')
    last_ip = f.read()
    return last_ip


def main():
    last_ip = get_last_ip()
    last_ip = last_ip.replace('\n','')
    local_ip = get_local_ip()
    print(last_ip)
    files1 = show_files('../simple-business', [])
    files2 = show_files('../init', [])
    files = []
    files.extend(files1)
    files.extend(files2)
    replace_ip(local_ip, last_ip, files)


if __name__ == '__main__':
    main()
